<?php

namespace app\common\behavior;

use addons\shopro\model\UserWalletLog;
use app\admin\model\LevelBuyLog;
use app\admin\model\UserLevelSetting;
use app\common\model\User;
use think\Db;

class UserUpgrade
{
    //private static $grade_type = ['user_level'=>'会员专区商品购买升级','invite'=>'邀请会员升级'];

    public function run(&$params)
    {
        $user = \addons\shopro\model\User::get($params['user_id']);
        $user_level_setting = UserLevelSetting::all();
        $levelIds = array_column($user_level_setting, 'level', 'id');
        if(!empty($user)){
            if ($user && $params['type'] == 'invite') {
                //当前用户邀请人数
                $invite_num = User::where(['pid' => $params['user_id']])->count();
                $new_user_level_setting = array_column($user_level_setting, 'invite_upgrade_num', 'level');

                if (isset($new_user_level_setting[$user['level'] + 1]) && $invite_num >= $new_user_level_setting[$user['level'] + 1]) {

                    $params['memo'] = '邀请会员升级';
                    $params['pay_type'] = 'invite';
                    $this->upgrade($user_level_setting, $user, $params);
                }
             //按等级顺序购买
            } else if ($user->level+1==$levelIds[$params['goods']['user_level_id']] && $params['type'] == 'user_level') {    //会员专区升级商品
            //} else if ($params['type'] == 'user_level') {    //会员专区升级商品

                $params['memo'] = '会员专区商品购买升级';
                $this->upgrade($user_level_setting, $user, $params);
            }elseif($params['type'] == 'user_level'){ //跨等级购买
                $params['memo'] = '会员专区商品购买升级';
                $this->upgrade2($user_level_setting, $user, $params);
            }
        }
    }

    //升级
    public function upgrade2($user_level_setting, $user, $params)
    {
        $newULevelSettingAwardScore = array_column($user_level_setting, 'award_score', 'level');
        $momArr = array_column($user_level_setting, 'mom', 'level');
        $upgrade_level = $params['goods']['user_level_id'];
        $unfreeze_day = config("site.unfreeze_day");
        $dj_score = 'level' . $upgrade_level . '_dj_score';
        $current_level = 'level' . $user['level'] . '_dj_score';
        //增加购买记录
        $level_buy_log = [
            'user_id' => $user->id,
            'level' => $upgrade_level,
            'money' => isset($params['goods']['price'])?$params['goods']['price']:0,
            'type' => $params['pay_type'],
            'ctime' => time(),
            'award_score' => $newULevelSettingAwardScore[$upgrade_level]
        ];
        $buy_log = LevelBuyLog::create($level_buy_log);
        //购买等级奖励积分
        \addons\shopro\model\User::score(bcmul($newULevelSettingAwardScore[$upgrade_level], $momArr[$upgrade_level]), $user->id, 'award_score', 0, $params['memo'] . '奖励积分', []);

        //获取等级设置
        $userLevelSetting = UserLevelSetting::where(['level' => $upgrade_level])->find();
        //是否有冻结的积分
        if ($userLevelSetting->freeze_score > 0) {
            //每天释放的数量
            $days_unfreeze = bcdiv($userLevelSetting->freeze_score, $unfreeze_day);
            //写冻结记录表
            $score_freeze_log = [
                'user_id' => $user->id,
                'unfreeze' => $userLevelSetting->freeze_score,
                'type' => $params['type']=='user_level'?1:2,
                'remark' => $params['memo'] . '等级' . $userLevelSetting->level . '冻结积分',
                'freeze_day' => $unfreeze_day,  //冻结的天数，
                'released_day' => 0,
                'status' => 1,
                'level' => $upgrade_level,
                'ctime' => time(),
                'days_unfreeze' => $days_unfreeze,
                'source' => $buy_log->id
            ];
            Db::name('score_freeze_log')->insert($score_freeze_log);
            //增加用户冻结的积分
            Db::name('user')->where(['id' => $user->id])->setInc($dj_score, $userLevelSetting->freeze_score);
            $before = bcsub($user->score, $user->$current_level, 2);
            //购买奖励的积分后 冻结积分
            $user_score_log = [
                'user_id' => $user->id,
                'score' => $userLevelSetting->freeze_score,
                'before' => $before,
                'after' => bcsub($before, $userLevelSetting->freeze_score),
                'memo' => $params['memo'] . '冻结等级' . $upgrade_level . '积分',
                'createtime' => time()
            ];
            Db::name('user_score_log')->insert($user_score_log);
            UserWalletLog::write($user, $userLevelSetting->freeze_score, $before, bcsub($before, $userLevelSetting->freeze_score), "freeze", $buy_log->id, "score", $params['memo'] . '冻结等级' . $upgrade_level . '积分', []);
            $list = Db::name('score_freeze_log')->where(['user_id'=>$user->id,'level'=>$user->level])->select();
            if($list){
                foreach ($list as $k=>$v){
                    Db::name('score_freeze_log')->where(['id'=>$v['id']])->update(['is_unfreeze'=>1]);
                }
            }
        }
        $user->level = $params['goods']['user_level_id'];
        $user->save();
    }

    //升级
    public function upgrade($user_level_setting, $user, $params)
    {
        $newULevelSettingAwardScore = array_column($user_level_setting, 'award_score', 'level');
        $momArr = array_column($user_level_setting, 'mom', 'level');
        $upgrade_level = $user['level'] + 1;
        $unfreeze_day = config("site.unfreeze_day");
        $dj_score = 'level' . $upgrade_level . '_dj_score';
        $current_level = 'level' . $user['level'] . '_dj_score';
        //增加购买记录
        $level_buy_log = [
            'user_id' => $user->id,
            'level' => $upgrade_level,
            'money' => isset($params['goods']['price'])?$params['goods']['price']:0,
            'type' => $params['pay_type'],
            'ctime' => time(),
            'award_score' => $newULevelSettingAwardScore[$upgrade_level]
        ];
        $buy_log = LevelBuyLog::create($level_buy_log);
        //购买等级奖励积分
        \addons\shopro\model\User::score(bcmul($newULevelSettingAwardScore[$upgrade_level], $momArr[$upgrade_level]), $user->id, 'award_score', 0, $params['memo'] . '奖励积分', []);

        //获取等级设置
        $userLevelSetting = UserLevelSetting::where(['level' => $upgrade_level])->find();
        //是否有冻结的积分
        if ($userLevelSetting->freeze_score > 0) {
            //每天释放的数量
            $days_unfreeze = bcdiv($userLevelSetting->freeze_score, $unfreeze_day);
            //写冻结记录表
            $score_freeze_log = [
                'user_id' => $user->id,
                'unfreeze' => $userLevelSetting->freeze_score,
                'type' => $params['type']=='user_level'?1:2,
                'remark' => $params['memo'] . '等级' . $userLevelSetting->level . '冻结积分',
                'freeze_day' => $unfreeze_day,  //冻结的天数，
                'released_day' => 0,
                'status' => 1,
                'level' => $upgrade_level,
                'ctime' => time(),
                'days_unfreeze' => $days_unfreeze,
                'source' => $buy_log->id
            ];
            Db::name('score_freeze_log')->insert($score_freeze_log);
            //增加用户冻结的积分
            Db::name('user')->where(['id' => $user->id])->setInc($dj_score, $userLevelSetting->freeze_score);
            $before = bcsub($user->score, $user->$current_level, 2);
            //购买奖励的积分后 冻结积分
            $user_score_log = [
                'user_id' => $user->id,
                'score' => $userLevelSetting->freeze_score,
                'before' => $before,
                'after' => bcsub($before, $userLevelSetting->freeze_score),
                'memo' => $params['memo'] . '冻结等级' . $upgrade_level . '积分',
                'createtime' => time()
            ];
            Db::name('user_score_log')->insert($user_score_log);
            UserWalletLog::write($user, $userLevelSetting->freeze_score, $before, bcsub($before, $userLevelSetting->freeze_score), "freeze", $buy_log->id, "score", $params['memo'] . '冻结等级' . $upgrade_level . '积分', []);
            $list = Db::name('score_freeze_log')->where(['user_id'=>$user->id,'level'=>$user->level])->select();
            if($list){
                foreach ($list as $k=>$v){
                    Db::name('score_freeze_log')->where(['id'=>$v['id']])->update(['is_unfreeze'=>1]);
                }
            }
            //冻结的积分是否解冻
            //if ($userLevelSetting->unfreeze == 1) {
                //Db::name('user')->where(['id' => $user->id])->setDec("$current_level", $user->$current_level);
                //增加解冻记录
//                $user_score_log = [
//                    'user_id' => $user->id,
//                    'score' => $user->$current_level,
//                    'before' => $before,
//                    'after' => bcadd($before, $user->$current_level),
//                    'memo' => '冻结的上一级积分解冻',
//                    'createtime' => time()
//                ];
//                Db::name('user_score_log')->insert($user_score_log);
                //Db::name('user')->where(['id' => $user->id])->setInc("score", $user->$current_level);
                //UserWalletLog::write($user, $user->$current_level, $before, bcadd($before, $user->$current_level), "unfreeze", $buy_log->id, "score", "冻结的上一级积分解冻", []);
                //解冻后删除对应用户对应等级的待释放积分
                //$list = Db::name('score_freeze_log')->where(['user_id'=>$user->id,'level'=>$user->level])->select();
                //                if($list){
                //                    foreach($list as $k=>$v){
                //                        Db::name('score_freeze_log')->where(['id'=>$v['id']])->update(['status'=>0]);
                //                    }
                //                }
            //}
        }
        $user->level += 1;
        $user->save();
    }

}
